<template>
	<div id="all-div">	
	<img src="../../public/img/小黄人.jpg" class="backgroundimage" />
		<div id="list-history" ref="myDiv">
			<div class="chat-list">
				<div class="history">历史记录</div>
			    <div v-for="(item, index) in chatHistory[0]" :key="index" class="chat-item">
			      <div class="chat-content" >
				  <div class="chat-user-name" :id="item.createDate"  @click="checkMessageInfo"><i class="el-icon-chat-dot-square"></i>&nbsp;&nbsp;&nbsp;{{item.userTalk}}</div>
				  <div class="chat-message" :id="item.createDate"  @click="checkMessageInfo">{{item.createDate}}</div>
			      </div>
			    </div>

			  </div>
		</div>
		<div>
			
		</div>
		<div>
				
			<div id="message">
				<div class="chatGptMessage">
					<div v-for="(message,index) in chatMessages" :key="index" class="message">
						<div id="1" v-if="message.isFormUser==1" class="userMassage">
							{{message.content}}
						</div>
						<div v-else  class="message-from-bot" >
							{{message.content}}
						</div>
				</div>

				</div>
			</div>
			<div class="text">
				欢迎您：{{username}}
			</div>
			<div class="exit">
				
			<el-dropdown ref="dropdown" class="avatar-dropdown">
			<span class="dropdown-trigger">
				
			<el-avatar icon="el-icon-user-solid" class="avatar" />
			</span>
			<el-dropdown-menu slot="dropdown">
			<el-dropdown-item @click.native="handleOptionClick('changeUserName')">修改用户名</el-dropdown-item>
			<el-dropdown-item @click.native="handleOptionClick('changepsw')">修改密码</el-dropdown-item>
			<el-dropdown-item @click.native="handleOptionClick('logout')">退出登录</el-dropdown-item>

			</el-dropdown-menu>
			</el-dropdown>

			</div>
		</div>

		<div class="input-text">
			<el-input
			  placeholder="请输入内容"
			  v-model="input"
			  clearable @keydown.enter.native="send"  tabindex="0">
			</el-input>
			
		</div>
		<div class="sendButton">
			<el-button type="primary" v-on:click="send" :disabled="sendButton" round>发送</el-button>
		</div>
<div class="newChat" @click="newChat">
	    <i>+&nbsp;&nbsp;new Chat</i>
</div>
	</div>
</template>

<!-- <template>
		
	<div class="chat-container">
	  <div class="chat-messages" ref="messages">
		<div v-for="(message, index) in chatMessages" :key="index" class="message">
		  <div v-if="message.isFromUser" class="message-from-user">{{ message.content }}</div>
		  <div v-else class="message-from-bot">{{ message.content }}</div>
		</div>
	  </div>
	  <div class="input-text">
			<el-input
			  placeholder="请输入内容"
			  v-model="input"
			  clearable>
			</el-input>
			
		</div>
		<div class="sendButton">
			<el-button type="primary" v-on:click="send"  round>发送</el-button>
		</div>
	</div>
  </template> -->
<script>
	import { Loading } from 'element-ui';

	import Request from '@/api/request';
	import axios from 'axios';
	import Changepsw from './ChangePasswordDialog.vue';
	export default{
		components: {
		     Changepsw
		  },

		data(){
			return{
				input:"",
				messages:"",
				chatMessages: [],
				inputs:"",
				chatHistory:[],
				numStars: 50, // 星星的数量
				// isChangePasswordDialogActive: false
				showChangePassword:false,
				newPassword:'',
				username:localStorage.getItem("username"),
				sendButton:false,
				chatReply:"1"
			}
		},
		mounted(){
			this.getAllList(1);
			this.animateStars();
			this.pushMessage();
			this.$nextTick(() => {
			    this.$refs.dropdown = this.$refs.dropdown || {};
			    this.$refs.dropdown.visible = false;
			  });
		},
		methods:{
			newChat(){
				this.chatMessages=[];
				const Message1={
					content : "你好，我是ChatGPT，能够通过自然语言与人类交互，帮助人们解决各种问题和困惑。我可以为你提供关于任何主题的信息和建议，包括学术研究、生活技巧、娱乐等等。同时，我也能够根据你的需求和兴趣生成各种文本，如文章、诗歌、小说等等。",
					isFormUser:0
				}	
				this.chatMessages.push(Message1)
				
			},
			    hideChangePasswordDialog() {
			      this.isChangePasswordDialogActive = false;
			    },
				showLoading() {
				const myDiv = this.$refs.myDiv;
  				this.loadingInstance = Loading.service({
				target:myDiv,
    			lock: true,
    			text: '加载中，请稍等...',
    			spinner: 'el-icon-loading',
    			background: 'rgba(0, 0, 0, 0.7)'
  				});
},
			handleOptionClick(option) {
				const tokens=localStorage.getItem("token");
				console.log(tokens)
				if(option=="logout"){
					const token=localStorage.getItem("token");
					Request.post('/user/logout')
					.then(res=>{
						if(res.data.code==200){
							localStorage.setItem("token","");
							this.$message({
							  message: '退出成功，正在跳转登录页面！',
							  type: 'success'
							});
							setTimeout(() => {
							  // 使用Vue.js的$router对象跳转页面
							  this.$router.push('/')
							}, 1500) // 3000毫秒即3秒钟
							this.$refs.dropdown.visible = false;
						}
					})
					
				}
				if(option == "changepsw"){
					 this.$prompt('请输入新密码', '提示', {
					      inputType: 'password',
					      inputPattern: /^.+$/,
					      inputErrorMessage: '密码不能为空'
					    }).then(({ value: password }) => {
					      this.$prompt('请再次输入新密码', '提示', {
					        inputType: 'password',
					        inputPattern: new RegExp(`^${password}$`),
					        inputErrorMessage: '两次输入的密码不一致'
					      }).then(({ value: confirmPassword }) => {
					        // 这里可以将密码提交给后台进行验证和更新
							this.newPassword=password;
							const id=localStorage.getItem("id");
							const uname=localStorage.getItem("username")
							console.log(id);
							console.log(uname)
							console.log(this.newPassword)
							Request.post("/user/changepsw",{id:id,username:uname,password:this.newPassword})
							.then(res=>{
								if(res.data.code==200){
									localStorage.setItem("token","");
									this.$message({
									  message: '密码修改成功，请重新登录！',
									  type: 'success'
									});
									setTimeout(() => {
									  // 使用Vue.js的$router对象跳转页面
									  this.$router.push('/')
									}, 1500) // 3000毫秒即3秒钟
									this.$refs.dropdown.visible = false;
								}
							})
					      }).catch(() => {});
					    }).catch(() => {
							this.$message({
			                  type: 'info',
			                  message: '取消输入'
			                });   
						});
						
						
				}
				if(option == "changeUserName")
			      this.$prompt('请输入新用户名', '提示', {
			                confirmButtonText: '确定',
			                cancelButtonText: '取消',
			                inputPattern: /^.+$/,
			                inputErrorMessage: '用户名不能为空'
			              }).then(({ value }) => {
			                this.$message({
			                  type: 'success',
			                  message: '您的新用户名为: ' + value
			                });
							if(value==localStorage.getItem("username")){
								this.$message.warning("您未做任何更改！")
							}
							else{
								const id=localStorage.getItem("id");
								const token=localStorage.getItem("token")
								const newUserName=value
								Request.post("/user/changeUserName",{id:id,username:newUserName})
								.then(res=>{
									if(res.data.code==200){
										localStorage.setItem("token","");
										this.$message({
										  message: '用户名修改成功，请重新登录！',
										  type: 'success'
										});
										setTimeout(() => {
										  // 使用Vue.js的$router对象跳转页面
										  this.$router.push('/')
										}, 1500) // 3000毫秒即3秒钟
										this.$refs.dropdown.visible = false;
										}
								})
							}
							
							
			              }).catch(() => {
			                this.$message({
			                  type: 'info',
			                  message: '取消输入'
			                });       
			              });
			    },
			showDropdown() {
			  this.$refs.dropdown.visible = true;
			},
			send:function(){
				if(this.input==""){
					this.$message.warning("输入框不能为空！")
				}
				if(this.chatReply==""){
					this.$message.warning("请等待消息回复完成再使用！")
				}
				else{
					this.senButton=1
					const userMessage={
						content : this.input,
						isFormUser:1
					}	
					this.chatMessages.push(userMessage)	
					this.inputs=this.input;
					this.input='';
					// axios({
					// 	url:"/talk/message",
					// 	method:"POST",
					// 	data: {
					// 	  message: this.inputs,
					// 	  userID: "1"
					// 	}
					// })
					this.chatReply="";
					Request({
						method:"post",
						url:'/talk/message',
						data:{
							message: this.inputs,
							userID: localStorage.getItem("id")
						}
					})
					// Request.post('/talk/message',{message: this.inputs,userID: "1"})
					.then(res=>{
						
						if(res.data.code==200){
							this.getAllList();
							this.chatReply=res.data.data
							this.senButton=0
							const botMessage={
								content : res.data.data,
								isFormUser:0
							}
							this.chatMessages.push(botMessage)		
						}
						else{
							this.messages="连接超时！"
							
						}
						
					})
					.catch(res=>{
						const botMessage={
							content : "连接超时！",
							isFormUser:0
						}
						this.chatMessages.push(botMessage)
						this.chatReply="连接超时"
					})
				}
				
			},
			getAllList:function(e){
				// axios({
				// 	url:"/api/talk/getAllList?userID=1",
				// 	// url:"http://54.163.5.153/talk/getAllList?userID=1",
				// 	method:"get",
				// })
				// Request.get('/talk/getAllList?userID=1')
				const userId=localStorage.getItem("id");
				this.showLoading();
				Request({
					method:"get",
					url:'talk/getAllList?userID='+userId
				})
				.then(res=>{
					if(res.data.code==200){
						this.chatHistory.push(res.data.data)
						console.log(this.chatHistory)
					}
					if(res.data.code==90002){
						this.$message.error("您还未登录，请先登录！");
						localStorage.setItem("token","")
						setTimeout(() => {
						  // 使用Vue.js的$router对象跳转页面
						  this.$router.push('/')
						  
						}, 1500) // 3000毫秒即3秒钟
						
					}
				}).catch(error=>{
					this.$message.error("服务器错误！请稍后再试！")
				}).finally(()=>{
					this.loadingInstance.close();
				})
			},
			checkMessageInfo:function(e){
				const createDate=e.target.getAttribute('id')
				// axios({
				// 	url:"talk/getMessageInfo?createDate="+createDate+"&userID=1",
				// 	method:"get",
				// })
				const userId=localStorage.getItem("id");
				Request({
					method:"get",
					url:"talk/getMessageInfo?createDate="+createDate+"&userID="+userId
				})
				// Request.get('/talk/getMessageInfo?createDate="+createDate+"&userID=1')
				.then(res=>{
					if(res.data.code==200){
						this.chatMessages=res.data.data
						console.log(res.data.data)
					}
				})
				
			},
			pushMessage(){
				const Message1={
					content : "你好，我是ChatGPT，能够通过自然语言与人类交互，帮助人们解决各种问题和困惑。我可以为你提供关于任何主题的信息和建议，包括学术研究、生活技巧、娱乐等等。同时，我也能够根据你的需求和兴趣生成各种文本，如文章、诗歌、小说等等。",
					isFormUser:0
				}	
				this.chatMessages.push(Message1)
			},
			
			animateStars() {
			      const stars = this.$el.querySelectorAll('.star');
			      stars.forEach(star => {
			        const delay = Math.random() * 10;
			        star.style.animationDelay = `${delay}s`;
			      });
			    }
		},
		
		}
</script>

<style scoped>
	.newChat{
		position: absolute;
		top:85%;
		left: 2%;
		color: #444654;
		background-color: rgba(255, 255, 255, 0.3);
		border-radius: 15px;
		text-align: center;
		height: 9%;
		width: 23%;
		font-family: fantasy;
		font-size: 50px;
		line-height: 70px;
		    -webkit-user-select:none;
		
		     -moz-user-select:none;
		
		     -ms-user-select:none;
		
		     user-select:none;
	}
	.text{
		position: absolute;
		left: 91%;
		top:2%;
		color: #2d2d2d;
	}
	.header {
  display: flex;
  justify-content: flex-end;
}
.change-password-message {
  display: flex;
  flex-direction: column;
}
.change-password-message .el-input {
  margin-bottom: 10px;
}
	.exit{
		position: absolute;
		top:5%;
		left: 96%;
	}
	.backgroundimage{
		width: 100%;
		height: 100%;
		position: fixed;
		top:0%;
		opacity: 0.5;
	}
	.box-card{
		position: absolute;
		top: 5%;
		left: 0%;
		width: 60%;
		height: 80%;
		background-color: rgba(255, 255, 255, 0.0);
		border-radius: 15px;
		overflow-y: auto;
	}
	.backgroundimages{
		width: 22%;
		height: 86%;
		position: fixed;
		left: 63.7%;
		top:0%;
	}
	.history{
		color: black;
		font-size: 24px;
		text-align: center;
		height: 5%;
		border-radius: 0.6;
	}
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 10px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
  width: 100%;
}

.message {
  padding: 5px;
  margin-bottom: 5px;
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
  
}

.userMassage {
  background-color: #95ec69;
  color: black;
 border-radius: 5px;
  padding: 10px;
  display: inline-block;
  max-width: 70%;
    opacity:0.9
}

.message-from-bot {
 background-color: #9acfea;
  color: #2d2d2d;
  border-radius: 5px;
  padding: 10px;
  display: inline-block;
  max-width: 900px;
  align-self: flex-end;
  opacity:0.9
/*    background-color: #f2f2f2;
    padding: 10px;
    border-radius: 10px;
    font-size: 14px;
    max-width: 80%; */
}

.chat-input {
  display: flex;
  align-items: center;
}

.chat-input input[type="text"] {
  flex: 1;
  padding: 10px;
  border-radius: 5px;
  border: none;
  outline: none;
  font-size: 16px;
  margin-right: 10px;
}


.image{
	position: absolute;
	width: 35px;
	height: 35px;
	left: 2%;
	border-radius: 15px;

}
.ChatGPT{
	position: absolute;
	left: 4%;
}
.chatGptMessage{
		  color: aliceblue;
		  /* max-width: 90%; */
		  margin-bottom: 8px;
		  padding: 8px;
		  border-radius: 12px;
		  align-self: flex-start;
		  /* background-color: #444654; */
		  position: relative; 
		  margin-right: 15%;
		  font-size: .875em;
		  margin-left: 10px;
		  line-height: 1.5;
		  white-space: pre-wrap;
		  border-radius: 8px;
		  padding: 10px;
		  /* display: flex; */
		  overflow :auto;
		  width: 90%;
	}
	#message{
		position: absolute;
		color: #f5f5f5;
		top: 1%;
		left: 25%;
		height: 600px;
		width: 900px;
		display: flex;
  		/* flex-direction: column; */
  		padding: 10px;
		display: flex;
		padding: 10px;
	overflow-y: auto;
	}
	#all-div{
		position: fixed;
		background-color: #444654;
		height: 100%;
		width: 100%;
		top:0;
		left: 0;
	}
	.star {
	  position: absolute;
	  top: calc(100% * Math.random());
	  left: calc(100% * Math.random());
	  width: 1px;
	  height: 1px;
	  background-color: white;
	  animation: starAnim 2s infinite;
	}
	
	@keyframes starAnim {
	  0% {
	    opacity: 1;
	  }
	  50% {
	    opacity: 0.5;
	  }
	  100% {
	    opacity: 1;
	  }
	  }
.send-btn:hover {
  background-color: #0066cc;
}
	#list-history{
		position: absolute;
		/* background-color:#d7d7d7; */
		background-color: rgba(255, 255, 255, 0.5);
		height: 80%;
		width: 23%;
		top:2%;
		left: 2%;
		color: black;
		overflow-y: auto;
		border-radius: 5px;
		opacity: 0.7;
		
	}
	.sendButton{
		position: fixed;
		position: absolute;
		top: 90%;
		left: 79%;
		height: 20px;
		width: 20px;
		
	}
	.textarea{
		position: fixed;
		height: auto;
		  resize: none;
		  min-height: 4%;
		  max-height: 50%;
	}
	.chat-list {
	position:absolute;
	top: 0px;
	left: 0px;
	width: 100%;
	height: 100%;
	overflow-y: scroll;
	}
	.chat-list::-webkit-scrollbar {
	width: 12px;
	}

	.chat-list::-webkit-scrollbar-track {
	background-color: #f5f5f5;
	}

	.chat-list::-webkit-scrollbar-thumb {
	background-color: #c7c7c7;
	border-radius: 10px;
	}

	.chat-list::-webkit-scrollbar-thumb:hover {
	background-color: #a1a1a1;
	}

	.chat-list::-webkit-scrollbar-corner {
	background-color: #f5f5f5;
	}

	.chat-item {
	  display: flex;
	 
	  align-items: center;
	  padding: 10px;
	  cursor: pointer;
	  transition: background-color 0.2s ease-in-out;
	  /* &:hover {
	    background-color: #f2f2f2;
	  } */
	  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
	    transition: box-shadow 0.3s ease-in-out; /* 添加过渡动画效果 */
		
	}
	::-webkit-scrollbar {
	  width: 10px; /* 设置滚动条宽度 */
	  height: 10px; /* 设置滚动条高度 */
	}
	
	/* 滚动条轨道样式 */
	::-webkit-scrollbar-track {
	  background-color: #f2f2f2; /* 设置滚动条轨道背景色 */
	  border-radius: 5px; /* 设置滚动条轨道的圆角 */
	}
	
	/* 滚动条滑块样式 */
	::-webkit-scrollbar-thumb {
	  background-color: #c2c2c2; /* 设置滚动条滑块背景色 */
	  border-radius: 5px; /* 设置滚动条滑块的圆角 */
	}
	
	/* 滚动条滑块鼠标悬停样式 */
	::-webkit-scrollbar-thumb:hover {
	  background-color: #a2a2a2; /* 设置滚动条滑块鼠标悬停时的背景色 */
	}
	div.chat-item:hover {
	  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); 
	  /* border: 1px solid #343541; */
	  border: 1px solid #877f7b;
	  border-radius: 5px;
	}
	
	.chat-avatar {
	  margin-right: 10px;
	}
	
	.chat-avatar img {
	  width: 50px;
	  height: 50px;
	  border-radius: 50%;
	}
	
	.chat-content {
	  flex: 1;
	  
	}
	
	.chat-user-name {
	  font-size: 20px;
	  font-weight: bold;
	  margin-bottom: 5px;
	  text-align: left;
	  
	}
	
	.chat-message {
	  font-size: 14px;
	  color: #666;
	  text-align: center;
	}
	
	.input-text{
		display: flex;
		position: absolute;
		top: 90%;
		width: 50%;
		height: 4%;
		left: 28%;
		background-color: #fff;
		align-items: center;
		border-radius: 25px;
		 box-shadow: 0px 0px 10px #ccc;
		 height: auto;
	}
	
</style>